package com.ssd.bd;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: SentinelAnnotationDemo
 * Description: 注解使用
 * date: 2020/6/30
 *
 * @author xugaojun
 */
public class SentinelAnnotationDemo {

    /**
     * 定义默认资源名
     */
    private static final String DEFAULT_RESOURCE_KEY = "HelloWorld";
    /**
     * 定义QPS模式下的阈值
     */
    private static final int QPS_COUNT = 1;

    public static void main(String[] args) throws InterruptedException {
        initFlowRules();
        // 死循环的原因是 直观看触发限流
        while (true) {
            // 1.5版本后 直接可 try-with-resource
            try (Entry entry = SphU.entry(DEFAULT_RESOURCE_KEY)) {
                // ====== 被保护的逻辑 ========
                sayHello();
            } catch (BlockException e) {
                System.out.println("触发限流");
            }
            // 因为阈值默认为1了 线程休眠 400MS
            Thread.sleep(400L);
        }
    }

    @SentinelResource(value = DEFAULT_RESOURCE_KEY)
    private static void sayHello() {
        System.out.println("Hello World");
    }

    /**
     * 初始化加载规则
     */
    private static void initFlowRules() {
        // 规则集合定义
        List<FlowRule> rules = new ArrayList<>();
        // 单个规则定义
        FlowRule rule = new FlowRule();
        // 设置资源名
        rule.setResource(DEFAULT_RESOURCE_KEY);
        // 设置限流模式
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置限流阈值 - 吞吐量模式即每秒可访问次数
        rule.setCount(QPS_COUNT);
        rules.add(rule);
        // 规则管理器加载规则
        FlowRuleManager.loadRules(rules);
    }

}
